// pages/add-data/add-data.js
import get from "lodash.get";
import map from "lodash.map";
import filter from "lodash.filter";
import omit from "lodash.omit";
import size from "lodash.size";
import Toast from "tdesign-miniprogram/toast/index";
import { addData, getGoodsList, getGroupList } from "../../api/order";
import { formatTime } from "../../utils/util";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    gridConfig: { column: 4 },
    showGroupPicker: false,
    groupList: [],
    nameOptions: [],
    form: {
      eventDate: formatTime(new Date(), true),
      userName: '',
      groupId: "",
      groupName: "",
      beforeImages: [],
      afterImages: [],
      remark: "",
      addr: "",
      goodsJson: [
        {
          name: "",
          type: "",
          goodsNum: "",
          unit: "",
        },
      ],
    },
  },
  // 分组
  async getGroupPickerData() {
    const [res] = await getGroupList({});
    this.setData({
      groupList: map(res?.data?.data?.groupList, (item) => ({
        label: item?.name,
        value: item?.id,
      })),
    });
  },
  // 商品列表
  async getGoodsPickerData() {
    const [res] = await getGoodsList({});
    console.log({ goodsList: res });
    this.setData({
      nameOptions: map(res?.data, (item) => ({
        ...item,
        label: item?.name,
        value: item?.id,
      })),
    });
  },
  onGroupPicker(e) {
    this.setData({
      showGroupPicker: true,
    });
  },
  onGroupPickerCancel(e) {
    this.setData({
      showGroupPicker: false,
    });
  },
  onGroupPickerConfirm(e) {
    this.setData({
      form: {
        ...this.data.form,
        groupId: get(e.detail.value, 0),
        groupName: get(e.detail.label, 0),
      },
    });
  },
  onChangeDesc(e) {
    this.setData({
      form: {
        ...this.data.form,
        remark: e.detail.value,
      },
    });
  },
  onChangeAddr(e) {
    this.setData({
      form: {
        ...this.data.form,
        addr: e.detail.value,
      },
    });
  },
  delGood(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      form: {
        ...this.data.form,
        goodsJson: filter(this.data.form.goodsJson, (v, idx) => idx !== index),
      },
    });
  },
  onAdd() {
    this.setData({
      form: {
        ...this.data.form,
        goodsJson: [...this.data.form.goodsJson, {}],
      },
    });
  },

  handleValueChange(e) {
    const operateKey = e.currentTarget.dataset.key;
    console.log("值变化:", e.detail, operateKey);
    const selectedItem = this.data.nameOptions.find(val => val?.id === e.detail?.selectedValue);
    console.log({ selectedItem })
    this.setData({
      form: {
        ...this.data.form,
        goodsJson: map(this.data.form.goodsJson, (v, idx) => {
          if (idx === operateKey) {
            if (selectedItem) {
              v = {
                ...v,
                id: selectedItem?.id,
                type: selectedItem?.type,
                unit: selectedItem?.unit,
                name: selectedItem?.name || e.detail.value,
              };
            } else {
              v = {
                ...v,
                name: e.detail.value,
              }
            }

          }
          return v;
        }),
      },
    });
  },
  onChangeNum(e) {
    const operateKey = e.currentTarget.dataset.key;
    this.setData({
      form: {
        ...this.data.form,
        goodsJson: map(this.data.form.goodsJson, (v, idx) => {
          if (idx === operateKey) {
            v = {
              ...v,
              goodsNum: Number(e.detail.value) || 0,
            };
          }
          return v;
        }),
      },
    });
  },
  onChangeMarque(e) {
    const operateKey = e.currentTarget.dataset.key;
    this.setData({
      form: {
        ...this.data.form,
        goodsJson: map(this.data.form.goodsJson, (v, idx) => {
          if (idx === operateKey) {
            v = {
              ...v,
              type: e.detail.value,
            };
          }
          return v;
        }),
      },
    });
  },
  onChangeUnit(e) {
    const operateKey = e.currentTarget.dataset.key;
    this.setData({
      form: {
        ...this.data.form,
        goodsJson: map(this.data.form.goodsJson, (v, idx) => {
          if (idx === operateKey) {
            v = {
              ...v,
              unit: e.detail.value,
            };
          }
          return v;
        }),
      },
    });
  },
  async handleAdd(e) {
    console.log({ e });
    const key = e.currentTarget.dataset.key;
    const fileList = get(this.data.form, [`${key}Images`], []);
    const { files } = e.detail;
    console.log({ files });

    const that = this;
    const waitFileList = [
      ...fileList,
      ...map(files, (file) => ({ ...file, percent: 0, status: "loading" })),
    ];
    console.log({ waitFileList });
    waitFileList.forEach((file, index) => {
      if (file.percent !== 100) {
        const task = wx.uploadFile({
          filePath: file.url,
          name: "file",
          url: `${getApp().globalData.BASE_URL}/upload/image`,
          formData: {
            memberId: wx.getStorageSync("userInfo")?.id,
            isSafe: "true",
          },
          success(res) {
            console.log({ res });
            let fileRes = {};
            try {
              fileRes = JSON.parse(res?.data);
            } catch (e) {
              console.log("parse file res error: ", e);
            }
            // 上传完成需要更新 fileList
            const fileList = get(that.data.form, [`${key}Images`], []);
            console.log({ fileList, fileRes });
            // const fileLen = fileList.length + index;
            that.setData({
              ...that.form,
              [`form.${key}Images[${index}].url`]: fileRes?.data,
              [`form.${key}Images[${index}].type`]: "image",
              [`form.${key}Images[${index}].percent`]: 100,
              [`form.${key}Images[${index}].status`]: "done",
            });
          },
          fail(error) {
            that.setData({
              ...that.form,
              [`form.${key}Images[${index}].percent`]: 100,
              [`form.${key}Images[${index}].status`]: "fail",
            });
            console.log({ error });
          },
        });
        task?.onProgressUpdate((res) => {
          console.log({ progress: res });
          console.log({ fileLen: fileList.length, index });
          that.setData({
            ...that.form,
            [`form.${key}Images[${index}].percent`]:
              res.progress === 100 ? 99 : res.progress,
            [`form.${key}Images[${index}].status`]: "loading",
          });
        });
      }
    });
  },
  handleRemove(e) {
    const key = e.currentTarget.dataset.key;
    const { index } = e.detail;
    const fileList = get(this.data.form, [`${key}Images`], []);
    fileList.splice(index, 1);
    this.setData({ ...this.form, [`form.${key}Images`]: fileList });
  },
  validateForm() {
    if (size(this.data.form.groupName) <= 0) {
      Toast({
        context: this,
        theme: "warning",
        selector: "#t-toast",
        message: "请选择分组",
      });
      return false;
    }
    if (size(this.data.form.remark) <= 0) {
      Toast({
        context: this,
        theme: "warning",
        selector: "#t-toast",
        message: "请输入维修情况说明",
      });
      return false;
    }
    if (size(this.data.form.addr) <= 0) {
      Toast({
        context: this,
        theme: "warning",
        selector: "#t-toast",
        message: "请输入地点",
      });
      return false;
    }
    // if (size(this.data.form.beforeImages) <= 0) {
    //   Toast({
    //     context: this,
    //     theme: "warning",
    //     selector: "#t-toast",
    //     message: "请上传维修前图片",
    //   });
    //   return false;
    // }
    // if (
    //   some(this.data.form.goodsJson, (item) => {
    //     return (
    //       size(item.type) === 0 ||
    //       size(item.goodsNum?.toString()) === 0 ||
    //       size(item.unit) === 0 ||
    //       size(item.name) === 0
    //     );
    //   })
    // ) {
    //   Toast({
    //     context: this,
    //     theme: "warning",
    //     selector: "#t-toast",
    //     message: "维修材料清单缺失字段",
    //   });
    //   return false;
    // }
    // if (size(this.data.form.afterImages) <= 0) {
    //   Toast({
    //     context: this,
    //     theme: "warning",
    //     selector: "#t-toast",
    //     message: "请上传维修后图片",
    //   });
    //   return false;
    // }
    return true;
  },
  async handleSubmit() {
    console.log({ form: this.data.form });
    console.log({ validte: this.validateForm() })
    if (this.validateForm()) {
      const goodsJson = filter(this.data.form.goodsJson, item => {
        return (
          size(item.type) > 0 ||
          size(item.goodsNum?.toString()) > 0 ||
          size(item.unit) > 0 ||
          size(item.name) > 0
        );
      })
      const result = omit({
        ...this.data.form,
        beforeImages: map(this.data.form.beforeImages, "url").join(","),
        afterImages: map(this.data.form.afterImages, "url").join(","),
        goodsJson: JSON.stringify(
          map(this.data.form.goodsJson, (item) => ({
            ...item,
          }))
        ),
      }, size(goodsJson) > 0 ? '' : 'goodsJson');
      console.log({ result });
      const [res] = await addData(result);
      if (res?.code?.toString() === "0") {
        Toast({
          context: this,
          theme: "success",
          selector: "#t-toast",
          message: "上报成功",
        });
        wx.navigateTo({
          url: "/pages/index/index",
        });
      } else {
        Toast({
          context: this,
          theme: "warning",
          selector: "#t-toast",
          message: "上报失败,请重试",
        });
      }
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) { },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() { },

  /**
   * 生命周期函数--监听页面显示
   */
  async onShow() {
    this.setData({
      form: {
        ...this.data.form,
        eventDate: formatTime(new Date(), true),
        userName: wx.getStorageSync("userInfo")?.name,
      },
    });
    await Promise.all([this.getGroupPickerData(), this.getGoodsPickerData()]);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() { },
});
